package org.tcp;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPThreadPoolServer extends TCPEchoServer{
    public TCPThreadPoolServer(int port) throws IOException {
        super(port);
    }
    @Override
    public void start() throws IOException {
        System.out.println("服务已启动，等待客户端连接.");
        //创建一个线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3,5,
                1, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(1));
        // 循环处理连接请求
        while(true) {
            // 接收客户端请求, 如果没有客户端连接就阻塞等待
            Socket clientSocket = socket.accept();
            // 把处理连接的操作加入了线程池中
            threadPool.submit(()->{
                processConnections (clientSocket);
            });

        }
    }
    public static void main(String[] args) throws IOException {
        TCPThreadServer server = new TCPThreadServer(9090);
        server.start();
    }
}
